package com.shenqi.parking.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.shenqi.parking.service.FileUploadService;
import com.shenqi.parking.service.impl.WechatAccessTokenService;
import com.shenqi.parking.service.impl.WechatMiniQrcodeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.shenqi.parking.domain.ParkingSpots;
import com.shenqi.parking.service.IParkingSpotsService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 车位出租Controller
 * 
 * @author shenqi
 * @date 2025-04-07
 */
@RestController
@RequestMapping("/parking/spots")
public class ParkingSpotsController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(ParkingSpotsController.class);

    @Autowired
    private IParkingSpotsService parkingSpotsService;

    @Autowired
    private FileUploadService fileUploadService;

    @Autowired
    private WechatAccessTokenService wechatAccessTokenService;

    @Autowired
    private WechatMiniQrcodeService wechatMiniQrcodeService;

    private final static String UPLOAD_FILEPATH = "spotImages";

    @PostMapping("/uploadSpotImage")
    public AjaxResult uploadSpotImages(MultipartFile file) throws IOException {
        String url = fileUploadService.uploadImage(file.getInputStream(), file.getOriginalFilename(), UPLOAD_FILEPATH);
        return AjaxResult.success("成功", url);
    }

    /**
     * 删除租赁意向
     */
    @DeleteMapping("/mine/{ids}")
    public AjaxResult removeMine(@PathVariable Long[] ids) {
        return toAjax(parkingSpotsService.deleteMyParkingSpotsByIds(ids));
    }

    /**
     * 查询车位出租列表
     */
//    @PreAuthorize("@ss.hasRole('parkinguser')")
    @Anonymous
    @GetMapping("/list")
    public TableDataInfo list(ParkingSpots parkingSpots)
    {
        startPage();
        List<ParkingSpots> list = parkingSpotsService.selectParkingSpotsList(parkingSpots);
        return getDataTable(list);
    }

    /**
     * 导出车位出租列表
     */
    @PreAuthorize("@ss.hasPermi('parking:spots:export')")
    @Log(title = "车位出租", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ParkingSpots parkingSpots)
    {
        List<ParkingSpots> list = parkingSpotsService.selectParkingSpotsList(parkingSpots);
        ExcelUtil<ParkingSpots> util = new ExcelUtil<ParkingSpots>(ParkingSpots.class);
        util.exportExcel(response, list, "车位出租数据");
    }

    /**
     * 获取车位出租详细信息
     */
//    @PreAuthorize("@ss.hasPermi('parking:spots:query')")
    @Anonymous
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(parkingSpotsService.selectParkingSpotsById(id));
    }

    /**
     * 新增车位出租
     */
    @PreAuthorize("@ss.hasPermi('parking:spots:add')")
    @Log(title = "车位出租", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ParkingSpots parkingSpots)
    {
        return toAjax(parkingSpotsService.insertParkingSpots(parkingSpots));
    }

    /**
     * 修改车位出租
     */
    @PreAuthorize("@ss.hasPermi('parking:spots:edit')")
    @Log(title = "车位出租", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ParkingSpots parkingSpots)
    {
        return toAjax(parkingSpotsService.updateParkingSpots(parkingSpots));
    }

    /**
     * 删除车位出租
     */
    @PreAuthorize("@ss.hasPermi('parking:spots:remove')")
    @Log(title = "车位出租", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(parkingSpotsService.deleteParkingSpotsByIds(ids));
    }



    @PreAuthorize("@ss.hasRole('parkinguser')")
    @GetMapping("/list/mine")
    public TableDataInfo listMine(ParkingSpots parkingSpots)
    {
        startPage();
        String username = SecurityUtils.getUsername();
        parkingSpots.setCreateBy(username);
        List<ParkingSpots> list = parkingSpotsService.selectParkingSpotsList(parkingSpots);
        return getDataTable(list);
    }
    /**
     * 新增车位出租
     */
//    @PreAuthorize("@ss.hasPermi('parking:spots:add')")
    @PreAuthorize("@ss.hasRole('parkinguser')")
    @Log(title = "车位出租", businessType = BusinessType.INSERT)
    @PostMapping("/mine")
    public AjaxResult addMine(@RequestBody ParkingSpots parkingSpots)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        parkingSpots.setCreateBy(loginUser.getUsername());
        return toAjax(parkingSpotsService.insertParkingSpots(parkingSpots));
    }

    /**
     * APP用户操作
     */
    /**
     * 删除车位出租
     */
//    @PreAuthorize("@ss.hasRole('parkinguser')")
//    @Log(title = "车位出租", businessType = BusinessType.DELETE)
//    @DeleteMapping("/mine/{id}")
//    public AjaxResult removeMine(@PathVariable Long id)
//    {
//        ParkingSpots spot = parkingSpotsService.selectParkingSpotsById(id);
//        String username = spot.getCreateBy();
//        if(!SecurityUtils.getUsername().equals(username)){
//            return AjaxResult.error("不能删除别人的数据哦");
//        }
//        return toAjax(parkingSpotsService.deleteParkingSpotsById(id));
//    }

    /**
     * 修改车位出租
     */
    @PreAuthorize("@ss.hasRole('parkinguser')")
    @Log(title = "车位出租", businessType = BusinessType.UPDATE)
    @PutMapping("/mine")
    public AjaxResult editMine(@RequestBody ParkingSpots parkingSpots)
    {
        ParkingSpots spot = parkingSpotsService.selectParkingSpotsById(parkingSpots.getId());
        if(!spot.getCreateBy().equals(SecurityUtils.getUsername())){
            return AjaxResult.error("不能更新别人的数据哦");
        }
        return toAjax(parkingSpotsService.updateParkingSpots(parkingSpots));
    }

    @PreAuthorize("@ss.hasRole('parkinguser')")
    @GetMapping("/genMiniCodeForPage")
    public void genMiniCodeForPage(
            @RequestParam String page,
            @RequestParam String scene,
            HttpServletResponse response) {
        try {
            // 1. 调用Service获取二进制数据（无HTTP依赖）
            byte[] qrcodeBytes = wechatMiniQrcodeService.generateQrcodeBytes(page, scene);

            // 2. Controller层统一设置响应头
            response.setContentType("image/png");
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + URLEncoder.encode("小程序码.png", "UTF-8"));
            response.setContentLength(qrcodeBytes.length);

            // 3. 写入响应流并flush
            try (OutputStream outputStream = response.getOutputStream()) {
                outputStream.write(qrcodeBytes);
                outputStream.flush(); // 此处flush符合Controller职责
            }
        } catch (IOException e) {
            log.error("响应流输出异常", e);
            // 可通过response设置错误状态码
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (RuntimeException e) {
            log.error("下载小程序码失败", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}
